package com.zzl.alligator.management.system.domain;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.zzl.alligator.common.util.AddressUtils;
import com.zzl.alligator.common.util.IpUtils;
import com.zzl.alligator.framework.base.domain.BaseEntity;
import com.zzl.alligator.framework.security.LoginUser;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


/**
 * 系统访问记录(SysLoginRecord)实体类
 *
 * @author zhouziliang
 * @since 2020-07-07
 */
@Data
@ToString
@Slf4j
public class SysLoginRecord extends BaseEntity {
    /**
     * 访问ID
     */
    private Long recordId;
    /**
     * 用户账号
     */
    private String userName;
    /**
     * 登录IP地址
     */
    private String ipaddr;
    /**
     * 登录地点
     */
    private String loginLocation;
    /**
     * 浏览器类型
     */
    private String browser;
    /**
     * 操作系统
     */
    private String os;
    /**
     * 登录状态（0成功 1失败）
     */
    private String status;
    /**
     * 提示消息
     */
    private String msg;
    /**
     * 访问时间
     */
    private LocalDateTime loginTime;


    public static SysLoginRecord buildLoginRecord(HttpServletRequest request, LoginUser loginUser, String status,
                                                String message) {
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        log.info(request.getHeader("User-Agent"));
        log.info(userAgent.toString());
        SysLoginRecord record = new SysLoginRecord();
        record.setUserName(loginUser.getUsername());
        if (userAgent.getBrowser() != null) {
            record.setBrowser(userAgent.getBrowser().getName());
        }
        record.setIpaddr(IpUtils.getIpAddr(request));
        record.setOs(userAgent.getOs().getName());
        record.setStatus(status);
        record.setMsg(message);
        record.setLoginTime(LocalDateTime.now());
        record.setLoginLocation(AddressUtils.getRealAddressByIp(record.getIpaddr()));
        return record;
    }
}